<?php
	include("includes/init.inc.php");
	require_once("includes/api.files.php");
	
	/* TODO: Add code here */
	$searchField = $_POST["search"]; // on re�oit le champs de la recherche en GET

	// on v�rifie AU MOINS que le champs de recherche ne soit pas vide
	if(trim($searchField) == ""){
		header( 'Location: main.php?search=emtpy' ) ;
		die();
	}

	// cherche le ID de l'usager
	$user_id = $_SESSION['user_id'];

	$fileName_array = array();
	$labelName_array = array();
	
	$temp = array();
	
	// TODO: COMMENTER CES LIGNES SI VOUS N'AVEZ PAS DE BD LOCALE
	mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWD) or die(mysql_error());
	mysql_select_db(DB_NAME) or die(mysql_error());
    
    $tokens = split(" ", $searchField);
    $extraWhereFile = "";
    $extraWhereLabel = "";
    foreach($tokens as $token) {
        if (trim($token) == "")
            continue;
        
        if($extraWhereFile == '') {
            $extraWhereFile = " AND (file.name LIKE '%{$token}%' ";
        } else {
            $extraWhereFile .= " OR file.name LIKE '%{$token}%' ";            
        }
    }
    if($extraWhereFile != "") {
        $extraWhereFile .= ')';
    }
    
    foreach($tokens as $token) {
        if (trim($token) == "")
            continue;
        $extraWhereLabel .= " AND EXISTS(SELECT * FROM label l2 
            INNER JOIN file_label fl ON 
                fl.label_id= l2.id
            WHERE fl.file_id=file.id AND l2.user_id={$user_id} AND l2.name LIKE '%{$token}%') ";
    }
    $sql = "SELECT 0 AS cat, file_id, file.name, file.file, file.ext, label.name AS label_name FROM file_label 
		INNER JOIN file ON
			file_label.file_id = file.id
		INNER JOIN label ON
			file_label.label_id = label.id 
		WHERE  label.user_id = {$user_id} {$extraWhereFile}
		GROUP BY file.id
		UNION ALL
		SELECT 1 AS cat, file_id, file.name, file.file, file.ext, label.name AS label_name FROM file_label 
		INNER JOIN file ON
			file_label.file_id = file.id
		INNER JOIN label ON
			file_label.label_id = label.id 
		WHERE  label.user_id = {$user_id} {$extraWhereLabel}
		GROUP BY file.id";
    //echo $sql;
	$result = mysql_query($sql) or die($sql.'<br>'.mysql_error());
	while($row = mysql_fetch_array( $result )){
		if($row[0] == 0){
			// si le nom cherché correspond au nom du fichier
			array_push(	
				$fileName_array, 
				array(
					"id" => $row[1], 
					"fileName" => $row[2]
				)
			);
		}
		else {
			// si le nom cherché correspond au nom du label
			array_push(	
				$labelName_array, 
				array(
					"id" => $row[1], 
					"fileName" => $row[2],
					"labelName" => $row[5]
				)
			);
		}
		if(!isset($temp[$row[1]]))
			$temp[$row[1]] = array();
		array_push($temp[$row[1]], '');
	}
	
	$filesScript = "<script>";
	$filesScript .= "files = ".json_encode($temp).";";
	$filesScript .= "</script>";
	
	include("includes/header.inc.php");
?>
				<?php echo $filesScript ?>
				<td id="contenu" style="height:300px;">
					<!-- Contenu commence ici -->
					
					<div class="searchResultSection">
					
						<div class="searchResultTitle"><?php echo "\"$searchField\""." found in the file's name..."?></div>
						<?php foreach ($fileName_array as $counter => $array): ?>
							<div class="displayFile" id="file<?php echo $array["id"] ?>">
								<div align="center"  onclick="clickedFileAction(<?php echo $array["id"] ?>)">
								<?php
									$info = get_file_info($array["id"]);
									echo '<img src="'.$info['icon'].'" alt="'.$info['name'].'"/>';
								?>
								</div>
								<div class="smallFileName"> <?php echo $array["fileName"] ?> </div>
								
							</div>
						<?php endforeach; ?>
						<div style="clear:both;"></div>
					</div>
					
					<div class="searchResultSection">
						<div class="searchResultTitle"><?php echo "\"$searchField\""." found in the label's name..."?></div>
						<?php foreach ($labelName_array as $counter => $array): ?>
							<div style="float:left; margin-left:10px; " id="file<?php echo $array["id"] ?>">
								<div align="center">
								<?php
									$info = get_file_info($array["id"]);
									echo '<img src="'.$info['icon'].'" alt="'.$info['name'].'"/>';
								?>
								</div>
								<div class="smallFileName"> 
									<?php echo $array["fileName"] ?><br/>
									(label: <?php echo $array["labelName"] ?>) 
								</div>
								
							</div>
						<?php endforeach; ?>
						<div style="clear:both;"></div>
					</div>
					
					<!-- Contenu fini ici -->
				</td>
<?php
	include("includes/footer.inc.php");
?>
